package com.companyname.demo.cod.scheduled;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 自定义ScheduledThreadPoolExecutor
 */
@Slf4j
public class CustomScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {

    public CustomScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, threadFactory, handler);
    }

    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        return super.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    /**
     * 该类存在的意义是重写ThreadPoolExecutor.afterExecute()方法，任务执行完后...
     */
    public void afterExecute(Runnable task, Throwable t) {
        BlockingQueue<Runnable> queue = super.getQueue();
        log.info("before remove queue.size ={}", queue.size());
        boolean removeFlag = false;
        try {
            removeFlag = queue.remove(task);
        } catch (Exception e) {
            log.error("****************remove task from queue failed***************",e.getMessage());
        }
        log.info("------------removeFlag={},after remove.queue.size={}------------", removeFlag, queue.size());
    }


}
